package com.cahnggou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName AuthorizeFilter
 * @Description 自定义全局过滤器
 * @Author Mr.L
 * @Date 21:41 2019/11/20
 * @Version 2.1
 **/
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    // 定义常量
    private static  final  String AUTHORIZE_TOKEN = "Authorization";

    // 登录页面
    private static final String LOGIN_URL = "http://localhost:9001/oauth/login";

    /**
     * 业务处理
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取request、response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 1、判断用户是否登陆操作，如果是，直接放行
        // 获取用户请求
        String url = request.getURI().getPath();
        // 登陆
//        if (url.startsWith("/api/user/login")){
//            return chain.filter(exchange);
//        }

        // 登录
        if (URLFilter.hasAuthorize(url)){
            return chain.filter(exchange);
        }


        // 2、其他请求，需要判断用户是否登陆（判断用户是否携带token信息）
        // 从请求参数获取token
        String token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        // 从请求头获取token
        if (StringUtils.isEmpty(token)){
            token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        }

        // 2.1 从cookie中获取token
        if (StringUtils.isEmpty(token)){
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie != null){
                token = cookie.getValue();
            }
        }

        // 3、如果没有token，不放行
        if (StringUtils.isEmpty(token)){
            System.out.println("弟弟没有登录");
            // 设置响应状态码
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setStatusCode(HttpStatus.SEE_OTHER);   // 303, 重定向到另一个url
            String path = LOGIN_URL + "?FROM=" + request.getURI().toString();
            response.getHeaders().add("Location", path);
            return response.setComplete();
        }

        // 4、token存在，需要解析
        try {
            // 解析成功
//            Claims claims = JwtUtil.parseJWT(token);
            request.mutate().header(AUTHORIZE_TOKEN, "bearer " + token);
        } catch (Exception e) {
            e.printStackTrace();
            // 解析失败  设置状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    /**
     * 过滤器执行的顺序
     * @return
     */
    @Override
    public int  getOrder() {
        return 0;
    }
}
